package cn.enilu.itnews.service;

import cn.enilu.itnews.entity.Comment;
import cn.enilu.itnews.entity.News;
import cn.enilu.itnews.model.CommentModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.enilu.flash.core.db.Pagination;
import cn.enilu.flash.core.db.Query;
import cn.enilu.flash.core.service.EntityService;
import cn.enilu.flash.web.QueryForm;

import java.util.List;

@Service
public class CommentService extends EntityService<Comment, Long> {
	private Logger logger = LoggerFactory.getLogger(CommentService.class);

	public CommentService() {
		super(Comment.class);
	}

	@Transactional
	public Pagination<CommentModel> search(QueryForm qf) {
		Query q = db.from(Comment.class);
		Pagination<CommentModel> pagination =  q.orderBy("id desc").paginate(CommentModel.class, qf.getPage());
		List<CommentModel> list = pagination.getData();
		if(list!=null&&list.size()>0){
			db.load(list);

		}
		return pagination;

	}

	public List<CommentModel> searchByNewsId(Long newsId) {
			List<CommentModel> list =  db.from(Comment.class).where("news_id",newsId).all(CommentModel.class);
			db.load(list);
			return list;
	}

	@Override
	public void create(Comment entity) {
		super.create(entity);
		News news = db.from(News.class).where("id",entity.getNewsId()).first(News.class);
		news.setCommentCount(news.getCommentCount()+1);
		db.update(news);
	}
}
